<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="handleAddWindow(0)">
        {{ $t('user_list.button.add') }}
      </el-button>
    </div>
    <el-table v-loading="listLoading" size="mini" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="{row}">
          <span>{{ row.Id }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" :label="$t('user_list.table.username')">
        <template slot-scope="{row}">
          <span>{{ row.Username }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" :label="$t('user_list.table.nickname')">
        <template slot-scope="{row}">
          <span>{{ row.Nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="70px" align="center" :label="$t('user_list.table.usertype')">
        <template slot-scope="{row}">
          <span>{{row.UserTypeName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" :label="$t('user_list.table.balance')">
        <template slot-scope="{row}">
          <span>{{ row.Balance }}</span>
        </template>
      </el-table-column>
      <el-table-column width="110px" align="center" :label="$t('user_list.table.score')">
        <template slot-scope="{row}">
          <span>{{ row.Score }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150px" :label="$t('user_list.table.register_time')" align="center">
        <template slot-scope="{row}">
          <span v-if="row.RegisterTime">{{ parseTime(row.RegisterTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" :label="$t('user_list.table.register_ip')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.RegisterIp }}</span>
        </template>
      </el-table-column>

      <el-table-column width="120px" :label="$t('user_list.table.last_login_ip')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.LastLoginIp }}</span>
        </template>
      </el-table-column>

      <el-table-column width="160px" :label="$t('user_list.table.last_login_time')" align="center">
        <template slot-scope="{row}">
          <span v-if="row.LastLoginTime">{{ parseTime(row.LastLoginTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column width="130px" :label="$t('user_list.table.lock')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.LockTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" :label="$t('user_list.table.state')" width="60">
        <template slot-scope="{row}">
          <i class="el-icon-check" style="color: green" v-if="row.State"></i>
          <i class="el-icon-close" style="color: red" v-if="!row.State"></i>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('user_list.table.operate')" width="240">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEditWindow(row)"
          >
            {{ $t('user_list.button.setting') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleStatus(row.Id)"
          >
            <span v-if="row.State">{{ $t('user_list.button.enable') }}</span>
            <span v-if="!row.State">{{ $t('user_list.button.disable') }}</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="searchData.page_index" :limit="searchData.page_size" :page-sizes="pageSizes" @pagination="getList" />

    <!-- 弹窗 新增 -->
    <el-dialog :title="$t('user_list.window.add_window_title')" :visible.sync="dialogAddFormVisible">
      <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-form-item :label="$t('user_list.window.add_field_user_type')" prop="type_id">
          <el-select v-model="addData.type_id" placeholder="请选择用户类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('user_list.window.add_field_username')" prop="username">
          <el-input v-model="addData.username" style="width: 380px;" />
        </el-form-item>
        <el-form-item :label="$t('user_list.window.add_field_nickname')" prop="nickname">
          <el-input v-model="addData.nickname" style="width: 380px;" placeholder="汉字,字母，数字,6 - 18个字符，汉字为3个字符"/>
        </el-form-item>
        <el-form-item :label="$t('user_list.window.add_field_is_tester')" prop="is_tester">
          <el-radio-group v-model="addData.is_tester">
            <el-radio-button label="0">{{$t('user_list.button.no')}}</el-radio-button>
            <el-radio-button label="1">{{$t('user_list.button.yes')}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('user_list.window.add_field_is_editor')" prop="is_tester">
          <el-radio-group v-model="addData.is_editor">
            <el-radio-button label="0">{{$t('user_list.button.no')}}</el-radio-button>
            <el-radio-button label="1">{{$t('user_list.button.yes')}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('user_list.window.add_field_login_password')" prop="password">
          <el-input type="password" v-model="addData.password" style="width: 380px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('user_list.button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleAddSubmit()">
          {{ $t('user_list.button.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗 设置  -->
    <el-dialog :title="$t('user_list.window.setting_window_title')" :visible.sync="dialogEditFormVisible">
      <div style="margin-bottom: 20px;"><el-divider content-position="left">{{ $t('user_list.window.setting_label_current_user') }} : {{ currentUser.Username }}</el-divider></div>
      <el-tabs tab-position="left" style="min-height: 400px;">
        <el-tab-pane :label="$t('user_list.window.setting_tab_fund')">
          <el-form ref="financeForm" :rules="financeRules" :model="financeData" label-position="left" label-width="160px" style="width: 800px; margin-left:50px;">
            <el-form-item :label="$t('user_list.window.setting_fund_field_type')" prop="flow_type">
              <el-radio-group v-model="financeData.flow_type">
                <el-radio-button label="in">{{ $t('user_list.options.fund_type_in') }}</el-radio-button>
                <el-radio-button label="out">{{ $t('user_list.options.fund_type_out') }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_fund_field_unit')" prop="finance_type">
              <el-radio-group v-model="financeData.finance_type">
                <el-radio-button label="coin">{{ $t('user_list.options.fund_target_coin') }}</el-radio-button>
                <el-radio-button label="score">{{ $t('user_list.options.fund_target_score') }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_fund_field_amount')" prop="amount">
              <el-input v-model="financeData.amount" placeholder="操作数量" style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_field_sec_password')" prop="sec_password">
              <el-input v-model="financeData.sec_password" placeholder="长度6 - 24位" show-password style="width: 380px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFinanceSubmit()">
                {{ $t('user_list.button.confirm') }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="$t('user_list.window.setting_tab_lock')">
          <el-form ref="lockForm" :rules="lockRules" :model="lockData" label-position="left" label-width="160px" style="width: 800px; margin-left:50px;">
            <el-form-item :label="$t('user_list.window.setting_lock_field_type')" prop="lock_type">
              <el-select v-model="lockData.lock_type">
                <el-option
                  v-for="item in lockOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_lock_field_target')" prop="lock_level">
              <el-select v-model="lockData.lock_level">
                <el-option
                  v-for="item in lockLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_lock_field_reason')" prop="lock_reason">
              <el-input v-model="lockData.lock_reason" placeholder="冻结原因" style="width: 380px;" />
            </el-form-item>
            <el-form-item :label="$t('user_list.window.setting_field_sec_password')" prop="sec_password">
              <el-input v-model="lockData.sec_password" placeholder="长度6 - 24位" show-password style="width: 380px;" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLockSubmit()">
                Confirm
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  userList, userAdd, userState, userFinance, userLock
} from '@/api/user'
import waves from '@/directive/waves'
import { parseTime } from '@/utils/index'
import Pagination from '@/components/Pagination'
import { strLength } from '@/utils/common'
import local from '@/lang/users/user_list'

export default {
  name: 'UserList',
  directives: { waves },
  components: { Pagination },
  data() {
    const checkNickname = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('Sorry，Nickname cant be empty!'))
      }

      const strLen = strLength(value)
      if (strLen > 18 || strLen < 6) {
        return callback(new Error('Sorry，Nickname mush be 6 - 18, Chinese Characher count as 3!'))
      }

      // 检测标签的字符构成
      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 标签只能包含汉字,数字,字母'))
      }

      callback()
    }

    const checkUsername = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起，用户名不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 18 || strLen < 6) {
        return callback(new Error('对不起，用户名长度为6-18个字!'))
      }

      // 检测标签的字符构成
      const reg = /^[A-Za-z]+[_A-Za-z0-9]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 标签只能包含数字,字母,下划线, 并且只能以字母开头'))
      }

      callback()
    }
    return {
      typeOptions: [],
      lockOptions: [],
      lockLevelOptions: [],
      list: [],
      pageSizes: [10, 15, 20, 25, 30, 50, 100],
      listLoading: true,
      currentAction: '添加管理员',
      total: 0,
      searchData: {
        page_index: 1,
        page_size: 15
      },
      currentUser: {},
      addData: {
        id: 0,
        type_id: '1',
        is_tester: 0,
        is_editor: 0,
        username: '',
        nickname: '',
        password: ''
      },
      financeData: {
        id: 0,
        flow_type: 'in',
        finance_type: 'coin',
        amount: 0,
        sec_password: ''
      },
      lockData: {
        id: 0,
        lock_type: '1',
        lock_level: 1,
        lock_reason: '',
        sec_password: ''
      },
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      rules: {
        type_id: [{ required: true, message: '需要选择类型', trigger: 'blur' }],
        username: [
          { required: true, message: '需要填写用户名', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '需要填写用户昵称', trigger: 'blur' },
          { validator: checkNickname, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '需要填写登陆密码', trigger: 'blur' },
          { min: 6, max: 24, message: '长度在 6 到 24 个字符之间', trigger: 'blur' }
        ],
        is_tester: [
          { required: true, message: '需要选择是否测试', trigger: 'blur' }
        ],
        is_editor: [
          { required: true, message: '需要选择是否编辑', trigger: 'blur' }
        ]
      },
      financeRules: {
        flow_type: [{ required: true, message: '需要选择走向类型', trigger: 'blur' }],
        finance_type: [{ required: true, message: '需要选择分值类型', trigger: 'blur' }],
        amount: [
          { required: true, message: '需要填写操作金额', trigger: 'blur' }
        ],
        sec_password: [
          { required: true, message: '需要填写安全密码', trigger: 'blur' },
          { min: 6, max: 24, message: '长度在 6 到 24 个字符之间', trigger: 'blur' }
        ]
      },
      lockRules: {
        lock_type: [{ required: true, message: '需要选择冻结类型', trigger: 'blur' }],
        lock_level: [{ required: true, message: '需要选择冻结目标', trigger: 'blur' }],
        lock_reason: [{ required: true, message: '需要填写冻结原因', trigger: 'blur' }],
        sec_password: [
          { required: true, message: '需要填写安全密码', trigger: 'blur' },
          { min: 6, max: 24, message: '长度在 6 到 24 个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    if (!this.$i18n.getLocaleMessage('en')['user_list']) {
      this.$i18n.mergeLocaleMessage('en', local.en)
      this.$i18n.mergeLocaleMessage('zh', local.zh)
      this.$i18n.mergeLocaleMessage('es', local.es)
      this.$i18n.mergeLocaleMessage('ja', local.ja)
    }
  },
  methods: {
    resetAddData() {
      this.addData = {
        id: 0,
        type_id: '1',
        is_tester: 0,
        is_editor: 0,
        username: '',
        nickname: '',
        password: ''
      }
    },
    getList() {
      this.listLoading = true
      userList(this.searchData).then(response => {
        this.list = response.data.data
        this.total = response.data.total

        this.lockOptions = response.data.lock_options
        this.typeOptions = response.data.type_options
        this.lockLevelOptions = response.data.lock_level_options

        setTimeout(() => {
          this.listLoading = false
        }, 1 * 300)
      })
    },
    handleFilter() {
      this.searchData.page_index = 1
      this.getList()
    },
    handleAddWindow() {
      this.resetAddData()
      this.dialogAddFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          userAdd(this.addData).then((response) => {
            if (response.success) {
              this.dialogAddFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleEditWindow(item) {
      this.resetFinanceData()
      this.resetLockData()
      this.currentUser = item

      this.lockData.lock_type = item.LockType + ''
      this.lockData.lock_reason = item.LockReason
      this.dialogEditFormVisible = true
    },
    handleFinanceSubmit() {
      this.$refs['financeForm'].validate((valid) => {
        if (valid) {
          this.financeData.id = this.currentUser.Id
          userFinance(this.financeData).then((response) => {
            if (response.success) {
              this.dialogFinanceFormVisible = false
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              this.getList()
              this.dialogEditFormVisible = false
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      })
    },
    resetFinanceData() {
      this.currentUser = {}
      this.financeData = {
        id: 0,
        flow_type: 'in',
        finance_type: 'coin',
        amount: 0,
        sec_password: ''
      }
    },
    handleLockSubmit() {
      this.$refs['lockForm'].validate((valid) => {
        if (valid) {
          this.lockData.id = this.currentUser.Id
          userLock(this.lockData).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '修改冻结类型成功!'
              })
              this.getList()
              this.dialogEditFormVisible = false
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    resetLockData() {
      this.currentUser = {}
      this.lockData = {
        id: 0,
        lock_type: '1',
        lock_level: '1',
        lock_reason: '',
        sec_password: ''
      }
    },
    handleStatus(id) {
      if (id === '' || id === undefined || id === null) {
        this.$message({
          type: 'error',
          message: '请选择用户'
        })
        return
      }

      const confirmTip = this.T_tips('state_change_confirm').toString()
      this.$confirm(confirmTip, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userState(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '设置成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'error',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.T_tips('change_cancel')
        })
      })
    },
    parseTime(time, format) {
      return parseTime(time, format)
    },
    T_tips(msg) {
      const hasKey = this.$te('user_list.tips.' + msg)
      if (hasKey) {
        const translatedMsg = this.$t('user_list.tips.' + msg)
        return translatedMsg
      }
      return msg
    }
  }
}
</script>
